<template>
  <div>
    <el-dialog title="分配角色" :model-value="roleToAssignDialogVisible" @open="handleOpen" :before-close="handleCancel"
      width="30%">
      <el-form :model="formData" :rules="rules" label-width="80px" ref="roleToAssignForm">
        <el-form-item label="角色名:" prop="checkedRoleIds">
          <el-checkbox-group v-model="formData.checkedRoleIds">
            <el-checkbox :value="role.id" :label="role.roleCnName" v-for="role in formCfg.roleList" :key="role.id" />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel()">取消</el-button>
        <el-button type="primary" @click="confirmCheck()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup name='RoleToAssign' lang='ts'>
import { ref, reactive } from 'vue'
import { addApi } from '@/api/userApi';
import { queryAllApi as listAllRoles } from '@/api/roleApi';
import { ElMessage } from 'element-plus';
import type { AnyObjsDefine } from '@/types/common.d.ts'

// 用户选择的角色
let formData = reactive({
  checkedRoleIds: [] as string[]
})
// 所有的角色
let formCfg = reactive({
  roleList: [] as AnyObjsDefine
})

let rules = reactive({
  checkedRoleIds: [
    { required: false,  trigger: 'blur' }
  ]
})

const props = defineProps<{ roleToAssignDialogVisible: boolean, roleIds: string[] }>()
let emitter = defineEmits(["closeDialog", "confirmCheck"])
let roleToAssignForm = ref()
// 打开对话框
const handleOpen = () => {
  // 查询所有的角色
  listAllRoles().then(result => {
    formCfg.roleList = result.data
  })
  // 赋值
  formData.checkedRoleIds = props.roleIds
}
// 取消
function handleCancel() {
  roleToAssignForm.value.resetFields()
  emitter("closeDialog")
}
// 确认选择
function confirmCheck(){
  if (formData.checkedRoleIds && formData.checkedRoleIds.length > 0) {
    emitter("confirmCheck", formData.checkedRoleIds)
  } else {
    ElMessage({ message: "请先选择角色", type: "warning" })
  }
}
</script>
<style scoped></style>